# -*- coding: utf-8 -*-
# @Time    : 2020/4/15 14:46
# @Author  : Desire
# @Email   : yangyin1106@163.com
# @Blog    : https://www.cnblogs.com/desireyang/
# @File    : DB_Handle.py
# @Software: PyCharm

import pymysql

from common.Yaml_Handle import yh

# 读取mysql数据库配置信息
mysql_data = yh.get_data("mysql")
print(mysql_data)


class MySqlHandle(object):
    """封装MySql数据库操作"""

    def __init__(self):
        # 创建数据库连接
        self.con = pymysql.connect(host=mysql_data["host"],
                                   user=mysql_data["user"],
                                   password=mysql_data["password"],
                                   port=mysql_data["port"],
                                   database=mysql_data["database"],
                                   charset='utf8')
        # 创建游标
        self.cur = self.con.cursor()

    def find_one(self, sql) -> tuple:
        """
        查找返回第一条数据
        :param sql:
        :return:
        """
        self.con.commit()
        self.cur.execute(sql)
        return self.cur.fetchone()

    def find_all(self, sql) -> tuple:
        """
        查找返回所有数据
        :param sql:
        :return:
        """
        self.con.commit()
        self.cur.execute(sql)
        return self.cur.fetchall()

    def count(self, sql) -> int:
        """
        返回数据条数
        :param sql:
        :return:
        """
        self.con.commit()
        return self.cur.execute(sql)

    def close(self):
        """关闭游标对象和断开连接"""
        self.cur.close()
        self.con.close()


